package plus.lgx.textsearcher.util;

import java.io.File;
import java.util.StringJoiner;

/**
 * Class name: PathUtil
 *
 * Create time: 12/21/22 9:24 AM
 *
 * @author lgx
 * @version 1.0
 */
public class PathUtil {

    public static String standardize(String filePath, boolean checkExist) {
        if (filePath.isBlank() || filePath.equals(".")) {
            return System.getProperty("user.dir");
        }
        if (filePath.equals("~")) {
            return System.getProperty("user.home");
        }
        if (filePath.equals("/")) {
            return "/";
        }

        String[] split, ans;
        int i = 1, j = 1;
        if (filePath.startsWith("~" + File.separator)) {
            split = (System.getProperty("user.home") + filePath.substring(1)).split(File.separator);
        } else {
            split = new File(filePath).getAbsolutePath().split(File.separator);
        }
        ans = new String[split.length];
        ans[0] = "";
        for (; i < split.length; i++) {
            if (".".equals(split[i]) || "".equals(split[i])) continue;
            if ("..".equals(split[i])) {
                if (j > 1) j--;
                continue;
            }
            ans[j++] = split[i];
        }
        if (j == 1) {
            return "/";
        }
        StringJoiner sj = new StringJoiner("/");
        for(i = 0; i < j; i++) {
            sj.add(ans[i]);
        }
        String ret = sj.toString();
        File f = new File(ret);
        if (checkExist && !f.exists()) {
            System.out.format("\"%s\": No such file or directory!%n", filePath);
            System.exit(6);
        }
        return ret;
    }

}
